package com.framework.zerocopy;

import java.io.*;
import java.nio.channels.FileChannel;

public class FileCopyDemo {
    @SuppressWarnings("resource")
    public static void transferToDemo(String from, String to) throws IOException {
        FileChannel fromChannel = new RandomAccessFile(from, "rw").getChannel();
        FileChannel toChannel = new RandomAccessFile(to, "rw").getChannel();
        long position = 0;
        long count = fromChannel.size();

        fromChannel.transferTo(position, count, toChannel);

        fromChannel.close();
        toChannel.close();
    }

    @SuppressWarnings("resource")
    public static void transferFromDemo(String from, String to)
            throws IOException {
        FileChannel fromChannel = new FileInputStream(from).getChannel();
        FileChannel toChannel = new FileOutputStream(to).getChannel();

        long position = 0;
        long count = fromChannel.size();

        toChannel.transferFrom(fromChannel, position, count);

        fromChannel.close();
        toChannel.close();
    }

    //验证传输同样文件时效率差距,只能单个测,第一次复制时已经加载,会有缓存导致第二次很快
    public static void main(String[] args) throws IOException {
        String from = "src/main/resources/1.data";
        String to = "src/main/resources/2.data";
        long start1 = System.currentTimeMillis();
        File s = new File(from);
        File t = new File(to);
        org.apache.commons.io.IOUtils.copy(new FileInputStream(s),new FileOutputStream(t));
        long end1 = System.currentTimeMillis();
        System.out.println((end1 - start1));


        long start = System.currentTimeMillis();
        //transferToDemo(from,to);
        transferFromDemo(from, to);
        long end = System.currentTimeMillis();
        System.out.println((end - start));


    }
}